package com.xuebusi.nio.client;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Scanner;

/**
 * NIO 客户端
 */
public class NioClient {

    public static String TCP_SERVER_ADDRESS = "127.0.0.1";
    public static final int TCP_SERVER_PORT = 8000;

    /**
     * 启动 NIO 客户端
     *
     * @param nickName
     * @throws IOException
     */
    public void start(String nickName) throws IOException {
        // 连接服务器端
        SocketChannel sc = SocketChannel.open(new InetSocketAddress(TCP_SERVER_ADDRESS, TCP_SERVER_PORT));

        // 接收服务器响应
        // 新开线程,专门负载接收服务器端的响应数据
        Selector selector = Selector.open();
        sc.configureBlocking(false);
        sc.register(selector, SelectionKey.OP_READ);
        new Thread(new NioClientHandler(selector)).start();

        // 从控制台模拟聊天 向服务器发送数据
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String request = scanner.nextLine();
            if (request != null && request.length() > 0) {
                sc.write(Charset.forName("UTF-8").encode(nickName + " : " + request));
            }
        }

    }
}
